//
//  StatusPictureView.swift
//  weibo
//
//  Created by 陈伟 on 15/10/20.
//  Copyright © 2015年 陈伟. All rights reserved.
//

import UIKit
import SDWebImage

//照片之间的距离
private let StatusPictureViewItemMargin: CGFloat = 8
private let  pictureViewCell = "pictureViewCell"
class StatusPictureView: UICollectionView {
    
    var viewModel: StatusViewModel? {
        didSet {
            sizeToFit()
            reloadData()
        }
    }
    
    private let width = UIScreen.mainScreen().bounds.width
    
    //sizeToFit 需重写sizeThatFits 方法
    override func sizeThatFits(size: CGSize) -> CGSize {
        return cellSize()
    }
    
    init(){
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = StatusPictureViewItemMargin
        layout.minimumInteritemSpacing = StatusPictureViewItemMargin
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        dataSource = self
        
        registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: pictureViewCell)
        backgroundColor = UIColor.init(white: 0.9, alpha: 1)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private var iconView: UIImageView = UIImageView()
    
//计算itemSize大小
    func cellSize() -> CGSize {
        
        //每行的照片数
        let rowCount: CGFloat = 3
        //最大宽度
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * statusCellMargin
        let itemWidth = (maxWidth - 2 * StatusPictureViewItemMargin)/rowCount
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        let count = viewModel?.thumbnailUrls?.count ?? 0
        
        if count == 0 {
            return CGSizeZero
        }
        
        if count == 1 {
            var imgSize = CGSize(width: 150, height: 120)

            if let key = viewModel?.thumbnailUrls?.first?.absoluteString {
                let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
                imgSize = image.size
            }
            
            imgSize.width = imgSize.width < 40 ? 40: imgSize.width
            if imgSize.width > 300 {
                let w: CGFloat = 300
                let h = imgSize.height * w/imgSize.width
                imgSize = CGSize(width: w, height: h)
            }
            layout.itemSize = imgSize
            
            
            return imgSize
        }
        
        if count == 4 {
            let w = StatusPictureViewItemMargin + 2 * itemWidth
            return CGSize(width: w, height: w)
        }
        
        let row = (count-1)/3 + 1
        let w = CGFloat(rowCount - 1 ) * StatusPictureViewItemMargin + CGFloat(rowCount) * itemWidth
        let h = CGFloat(row - 1) * StatusPictureViewItemMargin + CGFloat(row) * itemWidth
        return CGSize(width: w, height: h)
    }
    
}

//数据源方法
extension StatusPictureView: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureViewCell, forIndexPath: indexPath) as! StatusPictureCell
//        cell.backgroundColor = UIColor.redColor()
        cell.imageURL = viewModel?.thumbnailUrls![indexPath.item]
        return cell
    }
}

//
class StatusPictureCell: UICollectionViewCell{
    
    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL, placeholderImage: nil, options: [SDWebImageOptions.RetryFailed, SDWebImageOptions.RefreshCached])
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        contentView.addSubview(iconView)
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    private let iconView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        return iv
    }()
}
